package com.dede.monochromatism.fragment

import android.app.TimePickerDialog
import android.content.*
import android.os.Bundle
import android.preference.Preference
import android.preference.SwitchPreference
import android.provider.Settings
import com.dede.applib.extends.*
import com.dede.monochromatism.*
import com.dede.monochromatism.activity.AppListActivity
import com.dede.monochromatism.base.BasePreferenceFragment
import com.dede.monochromatism.db.ignoreTable
import com.dede.monochromatism.db.openTable
import com.dede.monochromatism.service.DbLoaderService
import com.dede.monochromatism.service.TimeJobService
import com.dede.monochromatism.util.UiUtil
import com.dede.monochromatism.util.Util
import org.jetbrains.anko.alert
import org.jetbrains.anko.startActivity
import org.jetbrains.anko.startService
import org.jetbrains.anko.toast
import java.util.*


/**
 * @author hsh
 * @date 2017/9/19 17:00.
 * @doc
 */
class SettingsFragment : BasePreferenceFragment<Boolean>() {

    override fun onSharedPreferenceChanged(sp: SharedPreferences, key: String) {
        when (key) {
            S_PRE_MONO -> {
                val state = sp.getBoolean(key, false)
                Util.setSimulateColorSpaceState(activity, state, {
                    sp.putBoolean(key, false)
                    sPreMono.isChecked = false
                    alert(R.string.permission_message, R.string.permission_title, {
                        positiveButton("复制命令", {
                            (activity.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager)
                                    .primaryClip = ClipData.newPlainText(null, getText(R.string.permission_adb))
                        })
                    }).show()
                })
            }
            S_PRE_STATUS -> {
                val state = sp.getBoolean(key, false)
                setStatus(state)
            }
            S_PRE_TIME -> {
                val state = sp.getBoolean(key, false)
                preOpenTime.isEnabled = state
                preCloseTime.isEnabled = state
                if (state) {
                    TimeJobService.registerJob(context())
                } else {
                    TimeJobService.cancelAllJob(context())
                }
            }
        }
    }

    private val calendar by lazy { Calendar.getInstance() }

    override fun onPreferenceClick(preference: Preference): Boolean {
        when (preference.key) {
            PRE_AUTO -> {
                startActivity<AppListActivity>("table" to openTable)
            }
            PRE_IGNORE -> {
                startActivity<AppListActivity>("table" to ignoreTable)
            }
            PRE_OPEN_TIME -> {
                val dialog = TimePickerDialog(context(),
                        R.style.TimePickerDialogTheme, { _, hourOfDay, minute ->
                    sp.putInt(openHour, hourOfDay)
                    sp.putInt(openMinute, minute)
                    preOpenTime.summary = UiUtil.getTime(hourOfDay, minute)
                }, sp.getInt(openHour, calendar.get(Calendar.HOUR_OF_DAY)),
                        sp.getInt(openMinute, calendar.get(Calendar.MINUTE)), false)
//                dialog.setTitle("选择开启的时间")
                dialog.setOnDismissListener {
                    TimeJobService.registerJob(context())
                }
                dialog.show()
            }
            PRE_CLOSE_TIME -> {
                val dialog = TimePickerDialog(context(),
                        R.style.TimePickerDialogTheme, { _, hourOfDay, minute ->
                    sp.putInt(closeHour, hourOfDay)
                    sp.putInt(closeMinute, minute)
                    preCloseTime.summary = UiUtil.getTime(hourOfDay, minute)
                }, sp.getInt(closeHour, calendar.get(Calendar.HOUR_OF_DAY)),
                        sp.getInt(closeMinute, calendar.get(Calendar.MINUTE)), false)
//                dialog.setTitle("选择关闭的时间")
                dialog.setOnDismissListener {
                    TimeJobService.registerJob(context())
                }
                dialog.show()
            }
        }
        return false
    }

    private val preAuto by lazy { findPreference(PRE_AUTO) }//自动开启应用
    private val preIgnore by lazy { findPreference(PRE_IGNORE) }//自动关闭应用
    private val preOpenTime by lazy { findPreference(PRE_OPEN_TIME) }
    private val preCloseTime by lazy { findPreference(PRE_CLOSE_TIME) }
    private val sPreMono by lazy { findPreference(S_PRE_MONO) as SwitchPreference }//预览

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        addPreferencesFromResource(R.xml.preference_settings)

        preAuto.onPreferenceClickListener = this
        preIgnore.onPreferenceClickListener = this
        preOpenTime.onPreferenceClickListener = this
        preCloseTime.onPreferenceClickListener = this

        var state = context().getBoolean(S_PRE_STATUS, false)
        setStatus(state)

        state = context().getBoolean(S_PRE_TIME, false)
        val openHour = context().getInt(openHour, 18)
        val openMinute = context().getInt(openMinute, 0)
        preOpenTime.summary = UiUtil.getTime(openHour, openMinute)
        preOpenTime.isEnabled = state

        val closeHour = context().getInt(closeHour, 6)
        val closeMinute = context().getInt(closeMinute, 0)
        preCloseTime.summary = UiUtil.getTime(closeHour, closeMinute)
        preCloseTime.isEnabled = state

        if (state)
            TimeJobService.registerJob(context())
    }

    private fun setStatus(state: Boolean) {
        preIgnore.isEnabled = state
        preAuto.isEnabled = state
        if (state) {
            Util.openAccessibilitySettings(activity, {
                toast("无障碍服务开启失败，请手动开启")
                activity.startActivity(Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS))
            })
            startService<DbLoaderService>()
        } else {
            Util.closeAccessibilitySettings(context())
        }
    }
}